package com.manager.devicemanager.controller;
import com.google.gson.JsonObject;
import com.manager.devicemanager.common.Result;
import com.manager.devicemanager.config.JwtUtil;
import com.manager.devicemanager.entity.UserInfo;
import com.manager.devicemanager.util.PWUtils;
import com.manager.devicemanager.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.manager.devicemanager.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import com.manager.devicemanager.vo.PageVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.tags.Tag;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wpf
 * @since 2025-05-17
 */
@Tag(name = "UserInfoController", description = " 相关接口")
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
    @Value("${user.default-password}")
    private String defaultPassword;
    @Autowired
    private IUserInfoService iUserInfoService;

    @Operation(summary = "新增")
    @PostMapping("/save")
    public Result<UserInfo> save(@Parameter(description = "UserInfo 对象") @RequestBody UserInfo userInfo){
        if (!iUserInfoService.isUsernameUnique(userInfo.getUsername(), null)) {
            return Result.error("用户名已存在，请重新输入");
        }
        userInfo.setPassword(PWUtils.encryptPassword(defaultPassword));
        userInfo.setIntime(Timestamp.from(new Date().toInstant()));
        iUserInfoService.save(userInfo);
        return Result.success(userInfo);
    }

    @Operation(summary = "按id删除")
    @PostMapping("/delete/{id}")
    public Result<String> delete(@Parameter(description = "记录ID", example = "1") @PathVariable("id") String id){
       iUserInfoService.removeById(id);
        return Result.success(id);
    }

    @Operation(summary = "按id修改")
    @PostMapping("/update/{id}")
    public Result<UserInfo> update(@Parameter(description = "记录ID", example = "1") @PathVariable("id") String id, @Parameter(description = "UserInfo 对象") @RequestBody UserInfo userInfo){
        userInfo.setId(id);
        UserInfo existingUser = iUserInfoService.getById(id);
        if (existingUser == null) {
            return Result.error("用户不存在");
        }
        if (!iUserInfoService.isUsernameUnique(userInfo.getUsername(), id)) {
            return Result.error("用户名已存在，请重新输入");
        }
       iUserInfoService.updateById(userInfo);
        return Result.success(userInfo);
    }

    @Operation(summary = "按id查询")
    @GetMapping("/get/{id}")
    public Result<UserInfo> get(@Parameter(description = "记录ID", example = "1") @PathVariable("id") String id){
        UserInfo userInfo =iUserInfoService.getById(id);
        userInfo.setPassword(null);
        return Result.success(userInfo);
    }

    @Operation(summary = "条件查询带分页")
    @PostMapping("/page")
    public Result<IPage<UserInfo>> page(@Parameter(description = "查询条件对象") @RequestBody PageVO<UserInfoVO> userInfoQuery){
        int pageNum = userInfoQuery.getPageNum();
        int pageSize = userInfoQuery.getPageSize();
        UserInfoVO userInfo = userInfoQuery.getCondition();


        //if (StringUtils.hasText(userInfo.getName())) {
          //  wrapper.like("name", userInfo.getName());
        //}

        IPage<UserInfo> userInfoList =iUserInfoService.pageWithoutPassword(new Page<>(pageNum, pageSize),userInfo );
        return Result.success(userInfoList);
    }

    @Operation(summary = "条件查询")
    @PostMapping("/list")
    public Result<List<UserInfo>> list(@Parameter(description = "UserInfo 查询条件对象") @RequestBody UserInfo userInfo){
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>(userInfo);
        userInfoQueryWrapper.select(UserInfo.class, info -> !"password".equals(info.getColumn()));
        List<UserInfo> userInfoList =iUserInfoService.list(userInfoQueryWrapper);
        return Result.success(userInfoList);
    }


    @Operation(summary = "重置用户密码")
    @PostMapping("/resetPassword/{id}")
    public Result<String> resetPassword(@Parameter(description = "用户 ID", example = "1") @PathVariable("id") String id) {
        boolean success = iUserInfoService.resetPassword(id);
        if (success) {
            return Result.success("密码重置成功");
        } else {
            return Result.error("密码重置失败，用户不存在");
        }
    }

    @Operation(summary = "修改用户密码")
    @PostMapping("/updatePassword/{id}")
    public Result<String> updatePassword(@Parameter(description = "用户 ID", example = "1") @PathVariable("id") String id,
                                         @Parameter(description = "旧密码", example = "123456") @RequestParam String oldPassword,
                                         @Parameter(description = "新密码", example = "654321") @RequestParam String newPassword) {
        boolean success = iUserInfoService.updatePassword(id, oldPassword, newPassword);
        if (success) {
            return Result.successAndMsg("密码修改成功");
        } else {
            return Result.error("密码修改失败，用户不存在或旧密码错误");
        }
    }


}
